﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Falafel.Assets.Resources;
using Falafel.Controls.Dialogs;
using Falafel.Services;
using Falafel.Services.Web.Models;
using System;
using System.ServiceModel.DomainServices.Client;

namespace Falafel.View
{
    public partial class Orders
    {
        public Orders()
        {
            InitializeComponent();
            Title = ApplicationStrings.HomePageTitle;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            // Register data events and load data into the View Model
            WebContext.Current.ViewModel.RegisterEvents(SubmittedChanges, LoadedData);
            WebContext.Current.ViewModel.Load();
        }

        protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            if (DataFormOrders.Mode != DataFormMode.ReadOnly)
            {
                // if the data form is in an altered mode, warn the user before continuing
                MessageDialog dlg = new MessageDialog("Are you sure you want to navigate away from the page when you have pending changes?",
                                                      "Navigation", DialogBaseType.Warning, DialogBaseButton.YesNo, e.Uri);
                dlg.Closed += NavigatingFromDialog_Closed;
                dlg.Show();
                e.Cancel = true;

                return;
            }

            // unregister the data events
            WebContext.Current.ViewModel.UnRegisterEvents(SubmittedChanges, LoadedData);
        }

        void NavigatingFromDialog_Closed(object sender, EventArgs e)
        {
            MessageDialog dlg = (MessageDialog)sender;
            if (dlg.DialogResult != true)
            {
                return;
            }

            DataFormOrders.CancelEdit();
            WebContext.Current.ViewModel.RejectChanges();

            NavigationService.Navigate((Uri)dlg.UserState);
        }

		private void SaveButton_Click(object sender, RoutedEventArgs e)
		{
            if (DataFormOrders.CurrentItem == null)
            {
                // if there's nothing to save, do nothing
                return;
            }

            // commit the changes to the entity set
            if (DataFormOrders.CommitEdit(true))
            {
                // save the changes to the database
                WebContext.Current.ViewModel.SubmitChanges();
            }
		}

        /// <summary>
        /// Method called when the View Model's Domain Data Source has submitted changes
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void SubmittedChanges(object sender, SubmittedChangesEventArgs args)
        {
            if (args.HasError)
            {
                args.MarkErrorAsHandled();

                ExceptionDialog dlg = new ExceptionDialog(args.Error, "Error Submitting Changes to the Database");
                dlg.Show();
            }
        }

        /// <summary>
        /// Method called when the View Model's Domain Data Source has loaded data
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private void LoadedData(object sender, LoadedDataEventArgs args)
        {
            if (args.HasError)
            {
                args.MarkErrorAsHandled();

                ExceptionDialog dlg = new ExceptionDialog(args.Error, "Error Loading Data from the Database");
                dlg.Show();
            }
        }

		private void CancelButton_Click(object sender, RoutedEventArgs e)
		{
            // cancel any view changes and tell the view model to revert any changes
            DataFormOrders.CancelEdit();
            WebContext.Current.ViewModel.RejectChanges();
		}

        private void EditButton_Click(object sender, RoutedEventArgs e)
        {
            // put the data form's view into edit mode
            DataFormOrders.BeginEdit();
        }

        private void AddButton_Click(object sender, RoutedEventArgs e)
        {
            // add a new Order to the data form's view
            DataFormOrders.AddNewItem();

        	Order CurrentOrder = DataFormOrders.CurrentItem as Order;
			if (CurrentOrder != null)
			{
                // set the default order date to the current time
				CurrentOrder.OrderDate = DateTime.Now;
			}
        }

        private void CaliforniaButton_Click(object sender, RoutedEventArgs e)
        {
            if (GridOrders.SelectedIndex == -1)
            {
                MessageDialog dlg = new MessageDialog("Please select an Order in the grid before moving the order to California.", "Select Item", DialogBaseType.Information,
                                                      DialogBaseButton.Ok);
                dlg.Show();
                return;
            }

            Order order = (Order)GridOrders.SelectedItem;
            WebContext.Current.ViewModel.MakeOrderCalifornia(order.ID, California_Completed);
        }

        private void California_Completed(InvokeOperation op)
        {
            if (op.HasError)
            {
                op.MarkErrorAsHandled();

                ExceptionDialog dlg = new ExceptionDialog(op.Error, "Cannot Change Order");
                dlg.Show();
                return;
            }

            // reload the data into the view model so the change shows in the view
            WebContext.Current.ViewModel.Reload();
        }

        private void TextBoxFilter_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            // set the filter descriptor
            WebContext.Current.ViewModel.SetFilterDescriptor(TextBoxFilter.Text);
        }
    }
}